# ------------------------------------------------------------------------------------------------
### Generate Table 6: Effects by government unit passing the resolution
# ------------------------------------------------------------------------------------------------

# Load data 
load("../data/results/sdid_results.Rda")

# Filter and prepare data - need to handle level filtering differently
filtered_results <- sdid_results %>%
  filter(
    outcome %in% c("Overall Turnout", "Party Turnout"),
    party %in% c("Opposition", "Overall Turnout", "Law and Justice (PiS)"),
    sum_level == "Any Level",
    sum_type == "Any Type",
    level != "Any Level",  # This is the key filter - exclude "Any Level" to get specific levels
    type == "Any Type",
    control_sample == "notyettreated",
    no300k_sample == "Full Sample",
    noproposed_sample == "Full Sample"
  ) %>%
  mutate(
    outcome = case_when(
      outcome == "Party Turnout" & party == "Opposition" ~ "Opposition Turnout",
      outcome == "Party Turnout" & party == "Law and Justice (PiS)" ~ "Government Turnout",
      TRUE ~ outcome
    ),
    outcome = factor(outcome, levels = c("Overall Turnout", "Opposition Turnout", "Government Turnout")),
    level = factor(level, levels = c("Province Level", "County Level", "Municipality Level"))
  ) %>%
  arrange(outcome, level)

# Generate and save table
latex_table <- create_latex_table(
  filtered_results,
  group_var = "outcome",
  row_var = "level",
  caption = "Synthetic Difference-in-Differences Estimates by Level of Government",
  label = "tab:sdid_by_level",
  col_names = c("Outcome", "Level", "Estimate (SE)", "N")
)

save_table(latex_table, "../output/tables/table6.txt")
